<template>
  <el-main>
    <el-form label-position="top" :model="noticeFormDate" :rules="rules" ref="noticeFormRef">
      <el-row>
        <el-col :md="19" :xs="17">
          <el-form-item prop="title" label="公告标题">
            <el-input v-model="noticeFormDate.title" show-word-limit maxlength="80" clearable></el-input>
          </el-form-item>
        </el-col>
        <el-col :md="{span:4,offset:1}" :xs="{span:6,offset:1}">
          <el-form-item prop="tid" label="公告类型">
            <el-select v-model="noticeFormDate.tid" placeholder="公告类型" clearable>
              <el-option
                v-for="(item,index) in noticeType"
                :key="index"
                :label="item.label"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :md="19" :xs="24">
          <el-form-item prop="content" label="公告内容">
            <TinymceEditor v-model="noticeFormDate.content" :bid="noticeFormDate.no" :height="'50vh'" />
          </el-form-item>
        </el-col>
        <el-col :md="{span:4,offset:1}" :xs="24">
          <el-row>
            <el-col>
              <el-form-item label="封面">
                <el-upload
                  :file-list="fileList"
                  ref="pic"
                  list-type="picture-card"
                  :class="showUploadButton ? 'uoloadSty' : 'disUoloadSty'"
                  action="#"
                  :http-request="requestUpload"
                  :on-preview="handlePictureCardPreview"
                  :limit="1"
                  :on-exceed="handleExceed"
                  accept=".png,.jpg,.jpeg"
                  :before-upload="beforeUpload"
                  :on-change="handleChange"
                  :on-remove="handleRemove"
                  >
                    <i slot="default" class="el-icon-plus"></i>
                </el-upload>
              </el-form-item>
            </el-col>
            <el-col>
              <el-row style="margin-top:30px" >
                <el-button v-if="hasPerm('msg:notice:create')" type="success" @click="sendNotice">立即发布</el-button>
                <el-button v-if="hasPerm('msg:notice:edit')" type="warning" @click="saveNotice">存为草稿</el-button>
              </el-row>
            </el-col>
          </el-row>
        </el-col>
      </el-row>
    </el-form>
    <el-dialog append-to-body :visible.sync="picsVisible">
      <img width="100%" :src="picsPreviewUrl" alt="">
    </el-dialog>
  </el-main>
</template>

<script>
import {
  uploadPicturesApi,
  getPicturesByBidApi,
  deletePicturesApi,
  deleteAllFilesApi
} from "@/api/pictures";
import {
  getNoticeTypeApi,
  saveNoticeApi
} from "@/api/notice"
import TinymceEditor from '@/components/Tinymce'
  export default {
    components: { TinymceEditor },
    props: {
      notice:{
        type:Object,
        default:null
      },
    },
    data(){
      return {
        //图片上传设置
        picsPreviewUrl: '',
        picsVisible: false,
        showUploadButton: true,
        fileList: [],
        deletePicsList: [],

        //新增或编辑表单验证规则
        rules: {
          title: { required: true, trigger: "blur", message: "标题不能为空" },
          tid: { required: true, trigger: "blur", message: "请选择公告类型" },
          content: { required: true, trigger: "blur", message: "内容不能为空" },
        },

        noticeType:'',
        choiceType:'',
        noticeFormDate:{
          title:'',
          content:'',
          tid:'',
          no:'',
          uid: this.$store.getters.userId,
          status:'',
        },
      }
    },
    created(){
      this.getNoticeType();
      //编辑不会立即传，创建会立即传
      if(this.notice!=null){
        this.noticeFormDate = this.notice;
      }
    },
    methods:{
      //获取公告类型
      async getNoticeType(){
        let res = await getNoticeTypeApi();
        if(res&&res.code==200){
          this.noticeType = res.data;
        }
      },
      //保存公告同时保存封面
      async saveNotice(){
        let readyUploadList = [];
        this.$refs.pic.uploadFiles.forEach(item=>{
          if(item.status==="ready"){
            readyUploadList.push(item)
          }
        })
        this.noticeFormDate.status = 0;
        let res = await saveNoticeApi(this.noticeFormDate);
        if(res&&res.code==200){
          //存在需要上传的图片
          if(readyUploadList.length>0){
            this.uploadPictures(readyUploadList,this.noticeFormDate.no)
          }
          //存在需要删除的图片
          if(this.deletePicsList.length>0){
            this.deletePictures(this.deletePicsList);
          }
          this.$store.dispatch('tagsView/delView', this.$route).then(() => {
            this.$router.replace({path:"/redirect/notice/edit/"+this.noticeFormDate.no});
          })
          this.$message.success(res.msg);
        }
      },
      //发布公告
      sendNotice(){
        let readyUploadList = [];
        this.$refs.pic.uploadFiles.forEach(item=>{
          if(item.status==="ready"){
            readyUploadList.push(item)
          }
        })
        this.$refs.noticeFormRef.validate(async (valid) => {
          if (valid) {
            this.noticeFormDate.status = 1;
            let res = await saveNoticeApi(this.noticeFormDate);
            if(res&&res.code==200){
              //存在需要上传的图片
              if(readyUploadList.length>0){
                this.uploadPictures(readyUploadList,this.noticeFormDate.no)
              }
              //存在需要删除的图片
              if(this.deletePicsList.length>0){
                this.deletePictures(this.deletePicsList);
              }
              //立即发布
              this.$store.dispatch('tagsView/delView', this.$route).then(() => {
                this.$router.replace({path:"/msg/notice"});
              })
              this.$message.success(res.msg);
            }
          }
        })
      },
      // 覆盖默认的上传行为
      requestUpload() {
      },
      // 上传预处理
      beforeUpload(file) {
        if (file.type.indexOf("image/") === -1) {
          this.$message.error("文件格式错误，请上传类型如：JPG、PNG后缀的图片！");
          return false;
        }
        if (file.size> 3145728) {
          this.$message.error("请上传大小不超过3M的图片！");
          return false;
        }
        return true;
      },
      handleExceed(){
        this.$message.info("最多选择上传一张图片，请重新选择！");
      },
      //删除图片
      handleRemove(file,filelist) {
        if(file.status==="success"){
          this.deletePicsList.push(file.id);
        }
        this.isShowUploadButton(filelist.length)
      },
      //提交图片
      handleChange(file,filelist){
        this.isShowUploadButton(filelist.length)
      },
      //预览图片
      handlePictureCardPreview(file) {
        this.picsPreviewUrl = file.url;
        this.picsVisible = true;
      },
      //判断是否显示上传按钮
      isShowUploadButton(listLength){
        if(listLength >= 1){
          this.showUploadButton = false;
        }else{
          this.showUploadButton = true;
        }
      },
      //获取图片
      async getPicturesByBid(bid){
        let res = await getPicturesByBidApi({"bid":bid})
        if(res&&res.code==200){
          this.fileList = res.data;
          this.isShowUploadButton(this.fileList.length);
        }
      },
      //上传图片
      async uploadPictures(list,bid){
        let formData = new FormData();
        list.forEach(item=>{
          formData.append("files",item.raw);
        })
        formData.append("bid",bid);
        await uploadPicturesApi(formData);
      },
      //确认删除图片
      async deletePictures(list){
        await deletePicturesApi({ids:list.toString()});
      },
    },
    watch:{
      notice(val){
        if(val){
          this.noticeFormDate = val;
          this.$set(this,'fileList',[]);
          this.getPicturesByBid(this.noticeFormDate.no);
        }
      }
    }
  }
</script>

<style lang="scss" scoped>
  .uoloadSty ::v-deep .el-upload--picture-card{
    width: 148px;
    height: 148px;
    line-height: 146px
    }
  .disUoloadSty ::v-deep .el-upload--picture-card{
    display:none;
    }
  .uoloadSty ::v-deep .el-upload-list__item {
    transition: none !important;
  }
  .disUoloadSty ::v-deep .el-upload-list__item {
    transition: none !important;
  }

</style>
